package com.lcz.mytest.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lcz.mytest.R;
import com.lcz.mytest.adapter.SeachStockAdapter;
import com.lcz.mytest.adapter.StockListAdapter;
import com.lcz.mytest.domain.SeachData;
import com.lcz.mytest.widget.CustomProgressDialog;
import com.lcz.mytest.widget.ToolBarActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/4/23.
 */
public class SeachActivity extends ToolBarActivity implements View.OnClickListener {

    private CustomProgressDialog loading_dialog;//加载提示
    private TextView startDate;//开始时间
    private TextView endDate;//结束时间
    private EditText price;//查找的定值
    private PullToRefreshListView seach_listview;//查询结果列表
    private int page = 1;
    private SQLiteDatabase db;
    private Button seach;
    private RelativeLayout start;
    private RelativeLayout end;
    private String newStartDate;
    private String max;

    int pageNum = 20;
    int count = 0;
    private List<String> seachList = new ArrayList<String>();
    //    private List<SeachData> seachCodeList = new ArrayList<SeachData>();
    private String currentCode;
    private SeachStockAdapter adapter;


    @Override
    protected void findViewById() {
        super.findViewById();
        setContentView(R.layout.seach);
        start = (RelativeLayout) findViewById(R.id.start);
        end = (RelativeLayout) findViewById(R.id.end);
        startDate = (TextView) findViewById(R.id.start_date);
        endDate = (TextView) findViewById(R.id.end_date);
        price = (EditText) findViewById(R.id.price);
        seach_listview = (PullToRefreshListView) findViewById(R.id.seach_listview);
        seach = (Button) findViewById(R.id.seach);
    }

    @Override
    protected void initView() {
        super.initView();
        getSupportActionBar().setTitle("多条件查询");
        seach.setOnClickListener(this);
        start.setOnClickListener(this);
        end.setOnClickListener(this);
        loading_dialog = new CustomProgressDialog(this, "加载中");
        copyDatabase();
        seach_listview.setMode(PullToRefreshBase.Mode.BOTH);
        seach_listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                showList(startDate.getText().toString(), endDate.getText().toString(), price.getText().toString(), page);
            }

            //上拉加载
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(SeachActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                page++;
                showList(startDate.getText().toString(), endDate.getText().toString(), price.getText().toString(), page);
            }
        });

        seach_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(SeachActivity.this, seachList.get(i - 1), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(SeachActivity.this, PastStockChartActivity.class);
                intent.putExtra("symbol", seachList.get(i - 1));
                intent.putExtra("startdate", startDate.getText().toString());
                intent.putExtra("enddate", endDate.getText().toString());
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }

    private void addList(List<SeachData> list) {
        for (int i = 0; i < 20; i++) {
            Cursor cursor2 = db.query("stock_daydata", new String[]{"code"},
                    "code=? and (date between ? and ?)and(close between ? and ?)",
                    new String[]{list.get(i).getCurrentCode(), list.get(i).getNewStartDate(), endDate.getText().toString(), price.getText().toString(), list.get(i).getMax()},
                    list.get(i).getCurrentCode(), null, null);

            while (cursor2.moveToNext()) {
                String theCode = cursor2.getString(cursor2.getColumnIndex("code"));
                seachList.add(theCode);
//                upData(seachList);
                System.out.println(theCode + "111111111");
            }
        }
    }

    /*查询列表
    * select code ,max(close),date from stock_daydata where
     (date between '2013-06-01' and '2014-08-01')GROUP BY code;
    select code ,close from stock_daydata where
    (date between '2013-09-12' and '2014-08-01')and (close between 5.34 and 12.25) GROUP BY code*/
    private void showList(final String startDate, final String endDate, final String price, final int page) {

        new AsyncTask<String, Integer, List>() {
            protected void onPreExecute() {
                loading_dialog.show();
            }

            @Override
            protected List doInBackground(String... params) {
                String code = params[0];
                if (db == null) {
                    db = SQLiteDatabase.openOrCreateDatabase(
                            getDatabasePath("stock").getAbsolutePath(), null);
                }

                // 查询
                /*获取指定时间内每支股票的最高收盘价，再将最高收盘价对应的时间作为新的开始时间查找符合给定值的股票*/
//                db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
                Cursor cursor = db.query("stock_daydata", new String[]{"code", "max(close)", "date"},
                        "date between ? and ?", new String[]{startDate, endDate}, "code", null, null);
                List<String> codeList = new ArrayList<String>();

                if (cursor != null) {

                    while (cursor.moveToNext()) {
                        newStartDate = cursor.getString(cursor.getColumnIndex("date"));
                        max = cursor.getString(cursor.getColumnIndex("max(close)"));
                        currentCode = cursor.getString(cursor.getColumnIndex("code"));

//                    codeList.add(new SeachData(newStartDate, max, currentCode));
//                    String sql = "select code from stock_daydata where (date between ? and ?)and (close between ? and ?)  GROUP BY code limit ?,?";
//                    Cursor cursor2 = db.rawQuery(sql, new String[]{newStartDate, endDate, price, max, (page - 1) * pageNum + "", pageNum + ""});
                        Cursor cursor2 = db.query("stock_daydata", new String[]{"code"},
                                "code=? and (date between ? and ?)and(close between ? and ?)",
                                new String[]{currentCode, newStartDate, endDate, price, max},
                                code, null, null, (page - 1) * pageNum + "," + pageNum);

                        if (count > pageNum) {
                            cursor2.move(pageNum * page);
                        }

                        while (cursor2.moveToNext()) {
                            count++;
                            String theCode = cursor2.getString(cursor.getColumnIndex("code"));
                            codeList.add(theCode);
                        }
                    }
                } else {
                    Toast.makeText(SeachActivity.this, "未能查找匹配的数据", Toast.LENGTH_SHORT).show();
                    return null;
                }
                return codeList;
            }

            protected void onPostExecute(List result) {
//                addList(result);
                upData(result);
                seach_listview.onRefreshComplete();
                loading_dialog.dismiss();
            }
        }.execute(startDate, endDate, price);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start:
                setDate(startDate);
                break;
            case R.id.end:
                setDate(endDate);
                break;
            case R.id.seach:
                //软键盘隐藏
                InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
                }
                showList(startDate.getText().toString(), endDate.getText().toString(), price.getText().toString(), page);
                break;
        }
    }

    //设置搜索时间
    public void setDate(final TextView tv) {
        final Calendar c = Calendar.getInstance();
        //获取用户的年、月、日初始化控件
        int y = Integer.parseInt(tv.getText().toString().substring(0, 4));
        int m = Integer.parseInt(tv.getText().toString().substring(tv.getText().toString().indexOf("-") + 1, tv.getText().toString().lastIndexOf("-")));
        int d = Integer.parseInt(tv.getText().toString().substring(tv.getText().toString().lastIndexOf("-") + 1));
        c.set(y, m - 1, d);//初始化弹出框的日期
        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // TODO Auto-generated method stub
                c.setTime(new Date());//再次初始化弹出框日期，得出当前系统时间
                //所选时间与当前系统时间比较
                String beginTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                String endTime = (String) DateFormat.format("yyyy-MM-dd", c.getTime());
                if (java.sql.Date.valueOf(beginTime).after(java.sql.Date.valueOf(endTime))) {
                    Toast.makeText(SeachActivity.this, "超出实际年份时间:" + endTime + "，请重新选择！！", Toast.LENGTH_SHORT).show();
                } else {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }


    //页面更新处理
    private void upData(List<String> list) {
        if (page == 1) {
            seachList.clear();//下拉刷新时清空
        }
        seachList.addAll(list);
        if (adapter == null) {
            adapter = new SeachStockAdapter(seachList, this);
            seach_listview.setAdapter(adapter);
        } else {
            adapter.upDataList(seachList);
            adapter.notifyDataSetChanged();
        }
    }

    //复制临时文件的数据库到手机中
    private void copyDatabase() {
        // 获取数据库文件
        final File file = getDatabasePath("stock");
        new AsyncTask<String, Integer, String>() {
            protected void onPreExecute() {
                loading_dialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                if (!file.exists()) {
                    try {
                        InputStream is = getAssets().open("stock");
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                        file.createNewFile();
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] bys = new byte[1024];
                        int len;
                        while ((len = is.read(bys)) != -1) {
                            fos.write(bys, 0, len);
                        }
                        is.close();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            protected void onPostExecute(String result) {
                loading_dialog.dismiss();
            }
        }.execute();
    }

    /*返回键返回主页重置下拉选项*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Intent intent = new Intent(SeachActivity.this, MainActivity.class);
            setResult(RESULT_OK, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
